import React, { Component } from 'react'
import MenuConfig from '../../config/menuConfig'
import { Menu } from 'antd';
// 引入redux
import { connect } from 'react-redux'
// 引入方法
import { switchMenu } from './../../redux/action'

import { NavLink } from 'react-router-dom' // 路由
import './index.less'

const { SubMenu } = Menu;

class NavLeft extends Component {

  state = {
    currentKey: ''
  }

  componentWillMount() {
    const menuTreeNode = this.renderMenu(MenuConfig)
    // let currentKey = window.location.hash.replace(/#|\?.*$/g,''); // 获取当前路由
    this.setState({
      // currentKey,
      menuTreeNode
    })
  }

  /**
   * 菜单点击
   */
  handleClick = ({item,key}) => {

    if (key == this.state.currentKey) {
      return false;
    }

    this.setState({
      currentKey: key
    });
    // 获取方法
    const { dispatch } = this.props;
    // 调用action
    dispatch(switchMenu(item.props.title))
  }

  /**
   * 菜单渲染,做一个循环递归
   * @param {Array} data 菜单数据
   */
  renderMenu = (data) => {
    return data.map(item => {
      if (item.children) { // 判断子节点生成submenu
        return (
          <SubMenu title={ item.title } key={ item.key }>
            { this.renderMenu(item.children) }
          </SubMenu>
        )
      }
      return <Menu.Item title={ item.title } key={ item.key }>
        <NavLink to={ item.key }>{ item.title }</NavLink>
      </Menu.Item>
    })

  }

  render() {
    return (
      <div>
          <div className="logo">
            <img src="/assets/logo-ant.svg" alt="" />
            <h1>Imooc MS</h1>
          </div>
        {/* 一个树列表 */ }
        <Menu theme='dark' onClick={ this.handleClick } mode="vertical">
          { this.state.menuTreeNode }
        </Menu>
      </div>
    )
  }
}

export default connect()(NavLeft);